package com.nanhai.buddhist.college.module.system.controller.admin.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Lists;
import com.nanhai.buddhist.college.framework.common.util.collection.CollectionUtils;
import com.nanhai.buddhist.college.framework.common.util.json.JsonUtils;
import com.nanhai.buddhist.college.module.collegebase.api.college.CollegeApi;
import com.nanhai.buddhist.college.module.collegebase.api.college.dto.CollegesRespDTO;
import com.nanhai.buddhist.college.module.system.api.user.dto.AdminUserRespDTO;
import com.nanhai.buddhist.college.module.system.controller.admin.user.vo.user.*;
import com.nanhai.buddhist.college.module.system.convert.permission.RoleConvert;
import com.nanhai.buddhist.college.module.system.convert.user.UserConvert;
import com.nanhai.buddhist.college.module.system.dal.dataobject.dept.DeptDO;
import com.nanhai.buddhist.college.module.system.dal.dataobject.permission.RoleDO;
import com.nanhai.buddhist.college.module.system.dal.dataobject.user.AdminUserDO;
import com.nanhai.buddhist.college.module.system.service.dept.DeptService;
import com.nanhai.buddhist.college.module.system.service.permission.PermissionService;
import com.nanhai.buddhist.college.module.system.service.permission.RoleService;
import com.nanhai.buddhist.college.module.system.service.user.AdminUserService;
import com.nanhai.buddhist.college.module.system.enums.common.SexEnum;
import com.nanhai.buddhist.college.framework.common.enums.CommonStatusEnum;
import com.nanhai.buddhist.college.framework.common.pojo.CommonResult;
import com.nanhai.buddhist.college.framework.common.pojo.PageResult;
import com.nanhai.buddhist.college.framework.common.util.collection.MapUtils;
import com.nanhai.buddhist.college.framework.excel.core.util.ExcelUtils;
import com.nanhai.buddhist.college.framework.operatelog.core.annotations.OperateLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.parameters.P;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static com.nanhai.buddhist.college.framework.common.pojo.CommonResult.success;
import static com.nanhai.buddhist.college.framework.common.util.collection.CollectionUtils.*;
import static com.nanhai.buddhist.college.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Api(tags = "管理后台 - 用户")
@RestController
@RequestMapping("/system/user")
@Validated
public class UserController {

    @Resource
    private AdminUserService userService;
    @Resource
    private DeptService deptService;


    @Resource
    private RoleService roleService;

    @Resource
    private PermissionService permissionService;
    @Resource
    private CollegeApi collegeApi;


    @PostMapping("/create")
    @ApiOperation("新增用户")
    @PreAuthorize("@ss.hasPermission('system:user:create')")
    public CommonResult<String> createUser(@Valid @RequestBody UserCreateReqVO reqVO) {
        String id = userService.createUser(reqVO);
        return success(id);
    }

    @PutMapping("update")
    @ApiOperation("修改用户")
    @PreAuthorize("@ss.hasPermission('system:user:update')")
    public CommonResult<Boolean> updateUser(@Valid @RequestBody UserUpdateReqVO reqVO) {
        userService.updateUser(reqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除用户")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = String.class)
    @PreAuthorize("@ss.hasPermission('system:user:delete')")
    public CommonResult<Boolean> deleteUser(@RequestParam("id") String id) {
        userService.deleteUser(id);
        return success(true);
    }

    @PutMapping("/update-password")
    @ApiOperation("重置用户密码")
    @PreAuthorize("@ss.hasPermission('system:user:update-password')")
    public CommonResult<Boolean> updateUserPassword(@Valid @RequestBody UserUpdatePasswordReqVO reqVO) {
        userService.updateUserPassword(reqVO.getId(), reqVO.getPassword());
        return success(true);
    }

    @PutMapping("/update-status")
    @ApiOperation("修改用户状态")
    @PreAuthorize("@ss.hasPermission('system:user:update')")
    public CommonResult<Boolean> updateUserStatus(@Valid @RequestBody UserUpdateStatusReqVO reqVO) {
        userService.updateUserStatus(reqVO.getId(), reqVO.getStatus());
        return success(true);
    }


    @GetMapping("/list")
    @ApiOperation("获取用户信息")
    public CommonResult<List<AdminUserRespDTO>> list(@RequestParam("ids") Collection<String> ids) {
        List<AdminUserDO> users = userService.getUsers(ids);
        return success(UserConvert.INSTANCE.convertList4(users));
    }

    @GetMapping("/page")
    @ApiOperation("获得用户分页列表")
    @PreAuthorize("@ss.hasPermission('system:user:list')")
    public CommonResult<PageResult<UserPageItemRespVO>> getUserPage(@Valid UserPageReqVO reqVO) {
        // 获得用户分页列表
        PageResult<AdminUserDO> pageResult = userService.getUserPage(reqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(new PageResult<>(pageResult.getTotal())); // 返回空
        }

        // 获得拼接需要的数据
//        Collection<Long> deptIds = convertList(pageResult.getList(), AdminUserDO::getDeptId);
//        Map<Long, DeptDO> deptMap = deptService.getDeptMap(deptIds);
//        // 拼接结果返回
        List<UserPageItemRespVO> userList = new ArrayList<>(pageResult.getList().size());
        pageResult.getList().forEach(user -> {
            UserPageItemRespVO respVO = UserConvert.INSTANCE.convert(user);
//            respVO.setDept(UserConvert.INSTANCE.convert(deptMap.get(user.getDeptId())));
            userList.add(respVO);
        });
        Set<String> collegeIds = new HashSet<>();
        pageResult.getList().forEach(s -> {
            if (null != s.getCollegeIds()) {
                collegeIds.addAll(s.getCollegeIds());
            }
        });

        PageResult<UserPageItemRespVO> userPageItemRespVOPageResult = new PageResult<>(userList, pageResult.getTotal());


        // 获取学院名称
        CommonResult<List<CollegesRespDTO>> collegesList = collegeApi.getCollegesAll();
        if (CollectionUtils.isNotEmpty(collegesList.getData())) {
            Map<String, CollegesRespDTO> stringCollegesRespDTOMap = convertMap(collegesList.getData(), CollegesRespDTO::getId);

            userPageItemRespVOPageResult.getList().forEach(s -> {
                ArrayList<String> objects = Lists.newArrayList();

                String permissionJson = s.getPermissionJson();
                if (Objects.nonNull(permissionJson)) {
                    //TODO null
                    Map map = JsonUtils.parseObject(permissionJson, Map.class);

                    map.keySet().stream().forEach(t -> {
                        String s1 = Optional.ofNullable(stringCollegesRespDTOMap).map(y -> y.get(t)).map(CollegesRespDTO::getCollegeName).orElse("");
                        if(StringUtils.isNoneBlank(s1)){

                            objects.add(s1);
                        }
                    });
//                    UserPermissionListVo userPermissionListVo = null;
//                    if (Objects.isNull(userPermissionListVo)) {
//                            objects.add(Optional.ofNullable(stringCollegesRespDTOMap).map(y -> y.get(t)).map(CollegesRespDTO::getCollegeName).orElse(""));
//                    }
//
//                    if (userPermissionListVo.isCollegeAll()) {
//                        objects.addAll(collegesList.getData().stream().map(CollegesRespDTO::getCollegeName).collect(Collectors.toList()));
//                    } else {
//                        Set<String> collegeId = userPermissionListVo.getCollegeId();
//                        collegeId.stream().forEach(t -> {
//                            objects.add(Optional.ofNullable(stringCollegesRespDTOMap).map(y -> y.get(t)).map(CollegesRespDTO::getCollegeName).orElse(""));
//                        });
//                    }
                }

                s.setCollegeName(objects);
            });
        }


        // 获取角色名称
        userPageItemRespVOPageResult.getList().forEach(s -> {
            List<RoleDO> roleListByUserId = roleService.getRoleListByUserId(s.getId());
            if (!roleListByUserId.isEmpty()) {
                s.setUserRoleVoList(RoleConvert.INSTANCE.convertList04(roleListByUserId));
            }
        });


        return success(userPageItemRespVOPageResult);
    }

    @GetMapping("/list-all-simple")
    @ApiOperation(value = "获取用户精简信息列表", notes = "只包含被开启的用户，主要用于前端的下拉选项")
    public CommonResult<List<UserSimpleRespVO>> getSimpleUsers() {
        // 获用户门列表，只要开启状态的
        List<AdminUserDO> list = userService.getUsersByStatus(CommonStatusEnum.ENABLE.getStatus());
        // 排序后，返回给前端
        return success(UserConvert.INSTANCE.convertList04(list));
    }

    @GetMapping("/get")
    @ApiOperation("获得用户详情")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('system:user:query')")
    public CommonResult<UserRespVO> getInfo(@RequestParam("id") String id) {
        UserPageItemRespVO convert = UserConvert.INSTANCE.convert(userService.getUser(id));
        if (ObjectUtil.isNotNull(convert.getRoleGroupId()) &&  convert.getRoleGroupId() == 0) {
            convert.setRoleGroupId(null);
        }
        Set<Long> userRoleIdListByUserId = permissionService.getUserRoleIdListByUserId(id);
        convert.setRoleIds(userRoleIdListByUserId);
        return success(convert);
    }

    @GetMapping("/export")
    @ApiOperation("导出用户")
    @PreAuthorize("@ss.hasPermission('system:user:export')")
    @OperateLog(type = EXPORT)
    public void exportUsers(@Validated UserExportReqVO reqVO,
                            HttpServletResponse response) throws IOException {
        // 获得用户列表
        List<AdminUserDO> users = userService.getUsers(reqVO);

        // 获得拼接需要的数据
        Collection<Long> deptIds = convertList(users, AdminUserDO::getDeptId);
        Map<Long, DeptDO> deptMap = deptService.getDeptMap(deptIds);
        Map<String, AdminUserDO> deptLeaderUserMap = userService.getUserMap(
                convertSet(deptMap.values(), DeptDO::getLeaderUserId));
        // 拼接数据
        List<UserExcelVO> excelUsers = new ArrayList<>(users.size());
        users.forEach(user -> {
            UserExcelVO excelVO = UserConvert.INSTANCE.convert02(user);
            // 设置部门
            MapUtils.findAndThen(deptMap, user.getDeptId(), dept -> {
                excelVO.setDeptName(dept.getName());
                // 设置部门负责人的名字
                MapUtils.findAndThen(deptLeaderUserMap, dept.getLeaderUserId(),
                        deptLeaderUser -> excelVO.setDeptLeaderNickname(deptLeaderUser.getNickname()));
            });
            excelUsers.add(excelVO);
        });

        // 输出
        ExcelUtils.write(response, "用户数据.xls", "用户列表", UserExcelVO.class, excelUsers);
    }

    @GetMapping("/get-import-template")
    @ApiOperation("获得导入用户模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<UserImportExcelVO> list = Arrays.asList(
                UserImportExcelVO.builder().username("xqenzo").deptId(1L).email("xqenzo@163.com").mobile("15601691300")
                        .nickname("xqenzo").status(CommonStatusEnum.ENABLE.getStatus()).sex(SexEnum.MALE.getSex()).build(),
                UserImportExcelVO.builder().username("xqenzo1").deptId(2L).email("xqenzo@163.com").mobile("15601701300")
                        .nickname("xqenzo1").status(CommonStatusEnum.DISABLE.getStatus()).sex(SexEnum.FEMALE.getSex()).build()
        );

        // 输出
        ExcelUtils.write(response, "用户导入模板.xls", "用户列表", UserImportExcelVO.class, list);
    }

    @PostMapping("/import")
    @ApiOperation("导入用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "Excel 文件", required = true, dataTypeClass = MultipartFile.class),
            @ApiImplicitParam(name = "updateSupport", value = "是否支持更新，默认为 false", example = "true", dataTypeClass = Boolean.class)
    })
    @PreAuthorize("@ss.hasPermission('system:user:import')")
    public CommonResult<UserImportRespVO> importExcel(@RequestParam("file") MultipartFile file,
                                                      @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        List<UserImportExcelVO> list = ExcelUtils.read(file, UserImportExcelVO.class);
        return success(userService.importUsers(list, updateSupport));
    }

}
